<template>
  <div class="app-container">
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="roomList"
      border
      fit
      highlight-current-row
      style="width: 100%"
      :default-sort="{prop: 'id'}"
      :row-key="getRowKeys"
      :expand-row-keys="expands"
      :row-style="TableRowStyle"
      @expand-change="toggleRowExpansion"
    >
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-form v-for="(user, idx) in scope.row.userlist" :key="idx" label-position="left" inline class="demo-table-expand" border="true">
            <el-row>
              <el-col :span="6">
                <el-form-item label="名字">
                  <span>{{ user.realName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="状态">
                  <el-tag :type="user.status | sessionStatusColorFilter">{{ user.status | sessionStatusFilter }}</el-tag>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="C索引">
                  <el-tag :type="user.rtcgwidx | callIdxColorFilter">{{ user.rtcgwidx | callIdxFilter }}</el-tag>
                </el-form-item>
                <el-form-item label="P索引">
                  <el-tag :type="user.zwmpidx | callIdxColorFilter">{{ user.zwmpidx | callIdxFilter }}</el-tag>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="音频发送">
                  <el-tag :type="user.sendaudio | sendRecvColorFilter">{{ user.sendaudio ? "发送":"未发送" }}</el-tag>
                  <el-tag :type="user.publishaudio | sendRecvColorFilter">{{ user.publishaudio ? "发布":"未发布" }}</el-tag>
                </el-form-item>
                <el-form-item label="音频接收">
                  <el-tag :type="user.recvaudio | sendRecvColorFilter">{{ user.recvaudio ? "接收":"未接收" }}</el-tag>
                  <el-tag :type="user.subscribeaudio | sendRecvColorFilter">{{ user.subscribeaudio ? "订阅":"未订阅" }}</el-tag>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="视频发送">
                  <el-tag :type="user.sendvideo | sendRecvColorFilter">{{ user.sendvideo ? "发送":"未发送" }}</el-tag>
                  <el-tag :type="user.publishvideo | sendRecvColorFilter">{{ user.publishvideo ? "发布":"未发布" }}</el-tag>
                </el-form-item>
                <el-form-item label="视频接收">
                  <el-tag :type="user.recvvideo | sendRecvColorFilter">{{ user.recvvideo ? "接收":"未接收" }}</el-tag>
                  <el-tag :type="user.subscribevideo | sendRecvColorFilter">{{ user.subscribevideo ? "订阅":"未订阅" }}</el-tag>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="操作">
                  <el-button type="primary" size="mini" @click="handleLog(user.sessionid)">
                    信令日志
                  </el-button>
                  <el-button type="success" size="mini" @click="handleQos(scope.row.room, user.realName)">
                    通道媒体
                  </el-button>
                  <el-button type="warning" size="mini" @click="handleZwmpChan(scope.row.pmodule, scope.row.room, user.realName)">
                    房间媒体
                  </el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column
        label="序号"
        prop="id"
        sortable
        align="center"
        min-width="20"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="scope">
          <span>{{ scope.$index }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" min-width="50" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="房间名称" min-width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.room }}</span>
        </template>
      </el-table-column>
      <el-table-column label="房间模式" min-width="50px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.mode | roomModeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最大画面数" min-width="30px">
        <template slot-scope="scope">
          <span>{{ scope.row.picnum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="画面模式" min-width="40px">
        <template slot-scope="scope">
          <span>{{ scope.row.picmode | picModeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="会议编号" min-width="50" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.id | roomIdFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="30"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button type="warning" size="mini" @click="handleRoom(scope.row)">
            会议日志
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
// import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { roomList } from '@/api/survery'
import { Message } from 'element-ui'
import { mapGetters } from 'vuex'

const itemTypeOptions = [
  { key: 'message', display_name: '消息' },
  { key: 'event', display_name: '事件' },
  { key: 'all', display_name: '全部' }
]

const itemProrityOptions = [
  { key: 1, display_name: '最多日志' },
  { key: 2, display_name: '普通事件' },
  { key: 3, display_name: '关键事件' },
  { key: 4, display_name: '严重错误' }
]

export default {
  name: 'ComplexTable',
  components: {},
  directives: { waves },
  filters: {
  },
  data() {
    return {
      sessionid: 0,
      tableKey: 0,
      roomList: [],
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        importance: 2,
        sessionID: undefined,
        sessionName: undefined,
        roomName: undefined,
        type: 'all',
        sort: '+id'
      },
      importanceOptions: itemProrityOptions,
      itemTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      detail: { prority: 0 },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        detail: '详情'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [
          { required: true, message: 'type is required', trigger: 'change' }
        ],
        timestamp: [
          {
            type: 'date',
            required: true,
            message: 'timestamp is required',
            trigger: 'change'
          }
        ],
        title: [
          { required: true, message: 'title is required', trigger: 'blur' }
        ]
      },
      downloadLoading: false,
      expands: []
    }
  },
  computed: {
    ...mapGetters([
      'currentExpands'
    ])
  },
  mounted() {
    this.getRoomList()
  },
  methods: {
    moduleTypeText(type) {
      const statusMap = {
        0: 'rtcgw', // rtcgw
        1: 'zwmp', // zwmp
        2: 'sip', // sip
        3: 'web', // web
        4: 'oam' // oam
      }
      return statusMap[type]
    },
    TableRowStyle({ row, rowIndex }) {
      const rowBackground = {}
      rowBackground.background = '#EBEEF5'
      return rowBackground
    },
    getRowKeys(row) {
      return row.room
    },
    toggleRowExpansion(row, expandedRows) { // 保存当前展开行供expand-row-keys属性使用
      this.expands = []
      expandedRows.forEach(element => {
        this.expands.push(element.room)
      })
      this.$store.dispatch('global/saveExpands', this.expands)
    },
    getRoomList() {
      const _this = this

      roomList().then(response => {
        _this.listLoading = false
        _this.roomList = response.data
        _this.expands = _this.currentExpands
      }).catch(error => {
        Message.error(error)
      })

      const timer = setInterval(() => {
        roomList().then(response => {
          _this.roomList = response.data
        }).catch(error => {
          Message.error(error)
        })
      }, 1200)

      // 通过$once来监听定时器，在beforeDestroy钩子可以被清除。
      this.$once('hook:beforeDestroy', () => {
        console.log('清除定时器')
        clearInterval(timer)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleQos(room, username) {
      this.$router.push({
        name: 'QOS',
        params: {
          room: room,
          username: username
        }
      })
    },
    handleZwmpChan(module, room, username) {
      this.$router.push({
        name: 'zwmpchans',
        params: {
          module: module,
          room: room,
          username: username
        }
      })
    },
    handleLog(sessionid) {
      this.$router.push({
        name: 'MessageLog',
        params: {
          sessionid: sessionid
        }
      })
    },
    handleRoom(row) {
      this.$router.push({
        name: 'MessageLog',
        params: {
          roomname: row.room
        }
      })
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    handleDetail(row, index) {
      this.detail = row
      this.dialogStatus = 'detail'
      this.dialogFormVisible = true
    },
    closeDetail() {
      this.dialogFormVisible = false
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then((excel) => {
        const tHeader = ['时间', '方向', '标题', '重要性', 'sessionid', '用户名', '房间名']
        const filterVal = [
          'time',
          'frommoduleno',
          'subject',
          'prority',
          'sessionid',
          'username',
          'roomname'
        ]
        const data = this.formatJson(filterVal)
        debugger
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'sessionid') {
            return v[j].toString()
          } else if (j === 'frommoduleno') {
            return this.moduleTypeText(v['frommodule']) + ' ' + v['frommoduleno'] + '->' +
              this.moduleTypeText(v['tomodule']) + ' ' + v['tomoduleno']
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

<style lang="scss" >
.box-card-component {
  .el-card__header {
    padding: 0px !important;
  }
  .el-card__body {
    padding: 0px !important;
  }
}
</style>
<style lang="scss" scoped>
.demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 100%;
  }
.box-card-component {
  .box-card-header {
    position: relative;
    height: 220px;
    img {
      width: 100%;
      height: 100%;
      transition: all 0.2s linear;
      &:hover {
        transform: scale(1.1, 1.1);
        filter: contrast(130%);
      }
    }
  }
  .card-panel-text {
    line-height: 18px;
    color: rgba(0, 0, 0, 0.55);
    font-size: medium;
    font-weight: bold;
    margin-top: 14px;
    margin-left: 14px;
  }
  .progress-item {
    margin-bottom: 10px;
    font-size: 14px;
  }
  .el-header,
  .el-footer {
    background-color: #b3c0d1;
    color: #333;
    text-align: center;
    line-height: 60px;
  }

  .el-aside {
    background-color: #d3dce6;
    color: #333;
    div {
      text-align: center;
      vertical-align: middle;
      display: table-cell;
      margin: auto;
    }
  }

  .el-main {
    background-color: #e9eef3;
    color: #333;
    text-align: center;
    vertical-align: middle;
    line-height: 40px;
  }

  body > .el-container {
    margin-bottom: 40px;
  }

  .el-container:nth-child(5) .el-aside,
  .el-container:nth-child(6) .el-aside {
    line-height: 260px;
  }

  .el-container:nth-child(7) .el-aside {
    line-height: 320px;
  }
  .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
    text-align: center;
    vertical-align: middle;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
  @media only screen and (max-width: 1510px) {
    .mallki-text {
      display: none;
    }
  }
}
</style>
